package com.bsoft.gol.editor.utils;


import ctd.access.AccessToken;
import ctd.access.controller.AccessTokenController;
import ctd.account.AccountCenter;
import ctd.account.UserRoleCurrentToken;
import ctd.account.UserRoleToken;
import ctd.account.UserRoleTokenDept;
import ctd.account.user.User;
import ctd.controller.exception.ControllerException;
import ctd.security.exception.SecurityException;
import ctd.util.JSONUtils;
import ctd.util.context.ContextUtils;
import ctd.util.converter.ConversionUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.List;

public class UserRoleTokenUtils {
    public static final String SESSION_UID_KEY = "uid";
    public static final String SESSION_TOKEN_KEY = "token";
    public static final String SESSION_WX_OPENID_KEY = "wx-openid";
    public static final String SESSION_WX_APPID_KEY = "wx-appid";
    public static final String SESSION_URT_DEPT = "urtDept";
    public static final String HEADER_ACCESS_TOKEN = "X-Access-Token";
    public static final String COOKIE_ACCESS_TOKEN = "tk";
    public static final String COOKIE_UID = "uid";
    public static final String COOKIE_URT = "urt";

    public UserRoleTokenUtils() {
    }

    public static String getSaltFromAccessToken(HttpServletRequest request) throws SecurityException {
        String tokenKey = request.getHeader("X-Access-Token");
        if (StringUtils.isEmpty(tokenKey)) {
            throw new SecurityException(SecurityException.ACCESS_DENIED, "accessToken is required.");
        } else {
            return tokenKey.substring(4, 8);
        }
    }

    public static UserRoleToken getByAccessToken(HttpServletRequest request) throws SecurityException {
        String tokenKey = request.getHeader("X-Access-Token");
        if (StringUtils.isEmpty(tokenKey)) {
            tokenKey = request.getHeader("token");
        }
        if (StringUtils.isEmpty(tokenKey)) {
            tokenKey = getAccessTokenFromCookie(request);
        }

        if (!StringUtils.isNotEmpty(tokenKey)) {
            throw new SecurityException(SecurityException.NOT_LOGON, "NotLogon");
        } else {
            String uid;
            String urt;
            try {
                AccessToken ac = (AccessToken)AccessTokenController.instance().get(tokenKey);
                if (AccessToken.isExpired(ac)) {
                    throw new SecurityException(SecurityException.TOKEN_EXPIRED, "accessToken[" + tokenKey + "] is expired");
                }

                uid = ac.getUserId();
                urt = ac.getUrt();
            } catch (ControllerException var5) {
                throw new SecurityException(404, "accessToken[" + tokenKey + "]  not found");
            }

            return getByUidAndUrt(uid, urt);
        }
    }

    public static UserRoleToken getUserRoleToken(HttpServletRequest request) throws SecurityException {
        HttpSession httpSession = request.getSession(false);
        if (httpSession != null) {
            String uid = (String)httpSession.getAttribute("uid");
            String urt = (String)httpSession.getAttribute("token");
            if (uid != null && urt != null) {
                return getByUidAndUrt(uid, urt);
            }
        }

        return getByAccessToken(request);
    }

    public static UserRoleCurrentToken getUserRoleCurrentToken(HttpServletRequest request) throws SecurityException {
        UserRoleCurrentToken userRoleTokenCurrent = null;
        HttpSession httpSession = request.getSession(false);
        boolean fromSession = false;
        String tokenKey;
        if (httpSession != null) {
            tokenKey = (String)httpSession.getAttribute("uid");
            if (StringUtils.isNotEmpty(tokenKey)) {
                fromSession = true;
            }
        }

        if (!fromSession) {
            tokenKey = request.getHeader("X-Access-Token");
            if (StringUtils.isEmpty(tokenKey)) {
                tokenKey = getAccessTokenFromCookie(request);
            }

            if (!StringUtils.isNotEmpty(tokenKey)) {
                throw new SecurityException(SecurityException.NOT_LOGON, "NotLogon");
            }

            try {
                AccessToken ac = (AccessToken)AccessTokenController.instance().get(tokenKey);
                if (AccessToken.isExpired(ac)) {
                    throw new SecurityException(SecurityException.TOKEN_EXPIRED, "accessToken[" + tokenKey + "] is expired");
                }

                userRoleTokenCurrent = getCurrentTokenByParam(ac.getUserId(), ac.getUrt(), ac.getUrtDept());
            } catch (ControllerException var7) {
                throw new SecurityException(404, "current token by accessToken[" + tokenKey + "] not found");
            }
        } else {
            tokenKey = (String)httpSession.getAttribute("uid");
            String urt = (String)httpSession.getAttribute("token");
            String urtDept = (String)httpSession.getAttribute("urtDept");
            if (!StringUtils.isNotEmpty(urt)) {
                throw new SecurityException(SecurityException.NOT_LOGON, "NotLogon");
            }

            userRoleTokenCurrent = getCurrentTokenByParam(tokenKey, urt, urtDept);
        }

        return userRoleTokenCurrent;
    }

    public static UserRoleCurrentToken getCurrentTokenByParam(String userId, String urtId, String urtDeptId) throws SecurityException {
        UserRoleToken userRoleToken = getByUidAndUrt(userId, urtId);
        UserRoleCurrentToken userRoleTokenCurrent = (UserRoleCurrentToken)JSONUtils.parse(JSONUtils.toString(userRoleToken), UserRoleCurrentToken.class);
        if (StringUtils.isNotEmpty(urtDeptId)) {
            List<UserRoleTokenDept> tokenDepts = userRoleToken.getUserRoleDepts();
            if (tokenDepts != null) {
                Iterator var6 = tokenDepts.iterator();

                UserRoleTokenDept tokenDept;
                do {
                    if (!var6.hasNext()) {
                        return userRoleTokenCurrent;
                    }

                    tokenDept = (UserRoleTokenDept)var6.next();
                } while(!tokenDept.getId().equals(urtDeptId) && !tokenDept.getDeptId().equals(urtDeptId));

                userRoleTokenCurrent = (UserRoleCurrentToken)JSONUtils.update(JSONUtils.toString(tokenDept), userRoleTokenCurrent);
                userRoleTokenCurrent.setCurrentDeptId(tokenDept.getDeptId());
                userRoleTokenCurrent.setId(userRoleToken.getId());
            }
        } else {
            userRoleTokenCurrent.setCurrentDeptId(userRoleToken.getDeptId());
        }

        return userRoleTokenCurrent;
    }

    public static String getCurrentDeptId(HttpServletRequest request) throws SecurityException {
        String deptId = null;
        HttpSession httpSession = request.getSession(false);
        boolean fromSession = false;
        String tokenKey;
        if (httpSession != null) {
            tokenKey = (String)httpSession.getAttribute("uid");
            if (StringUtils.isNotEmpty(tokenKey)) {
                fromSession = true;
            }
        }

        List tokenDepts;
        Iterator var9;
        UserRoleTokenDept tokenDept;
        if (!fromSession) {
            tokenKey = request.getHeader("X-Access-Token");
            if (StringUtils.isEmpty(tokenKey)) {
                tokenKey = getAccessTokenFromCookie(request);
            }

            if (StringUtils.isNotEmpty(tokenKey)) {
                try {
                    AccessToken ac = (AccessToken)AccessTokenController.instance().get(tokenKey);
                    if (AccessToken.isExpired(ac)) {
                        throw new SecurityException(SecurityException.TOKEN_EXPIRED, "accessToken[" + tokenKey + "] is expired");
                    }

                    UserRoleToken userRoleToken = getByUidAndUrt(ac.getUserId(), ac.getUrt());
                    deptId = userRoleToken.getDeptId();
                    String urtDeptId = ac.getUrtDept();
                    if (StringUtils.isNotEmpty(urtDeptId)) {
                        tokenDepts = userRoleToken.getUserRoleDepts();
                        if (tokenDepts != null) {
                            var9 = tokenDepts.iterator();

                            while(var9.hasNext()) {
                                tokenDept = (UserRoleTokenDept)var9.next();
                                if (tokenDept.getId().equals(urtDeptId)) {
                                    deptId = tokenDept.getDeptId();
                                    break;
                                }
                            }
                        }
                    }
                } catch (ControllerException var11) {
                    throw new SecurityException(404, "current deptId by accessToken[" + tokenKey + "] not found");
                }
            }
        } else {
            tokenKey = (String)httpSession.getAttribute("uid");
            String urt = (String)httpSession.getAttribute("token");
            String urtDeptId = (String)httpSession.getAttribute("urtDept");
            UserRoleToken userRoleToken = getByUidAndUrt(tokenKey, urt);
            deptId = userRoleToken.getDeptId();
            if (StringUtils.isNotEmpty(urtDeptId)) {
                tokenDepts = userRoleToken.getUserRoleDepts();
                if (tokenDepts != null) {
                    var9 = tokenDepts.iterator();

                    while(var9.hasNext()) {
                        tokenDept = (UserRoleTokenDept)var9.next();
                        if (tokenDept.getId().equals(urtDeptId)) {
                            deptId = tokenDept.getDeptId();
                            break;
                        }
                    }
                }
            }
        }

        return deptId;
    }

    public static UserRoleToken getByUidAndUrt(String uid, String urt) throws SecurityException {
        UserRoleToken token;
        try {
            User user = AccountCenter.getUser(uid);
            token = user.getUserRoleToken(urt);
        } catch (ControllerException var4) {
            throw new SecurityException(404, "user[" + uid + "] not found");
        }

        if (token == null) {
            throw new SecurityException(404, "userRoleToken[" + urt + "] for user[" + uid + "] not found");
        } else {
            String tenantId = token.getTenantId();
            if (StringUtils.isNotEmpty(tenantId)) {
                ContextUtils.put("$tenantId", tenantId);
            }

            return token;
        }
    }

    public static Cookie findCookie(HttpServletRequest request, String id, boolean httpOnly) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            Cookie[] var4 = cookies;
            int var5 = cookies.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                Cookie c = var4[var6];
                if (c.getName().equals(id)) {
                    return c;
                }
            }
        }

        return null;
    }

    public static void addCookie(HttpServletRequest request, HttpServletResponse response, String id, Object val, boolean httpOnly, int expires) {
        Cookie c = new Cookie(id, (String)ConversionUtils.convert(val, String.class));
        c.setHttpOnly(httpOnly);
        c.setMaxAge(expires);
        String cp = request.getContextPath();
        if (StringUtils.isNotEmpty(cp)) {
            c.setPath(cp);
        } else {
            c.setPath("/");
        }

        response.addCookie(c);
    }

    public static void addCookie(HttpServletRequest request, HttpServletResponse response, String id, Object val, int expires) {
        addCookie(request, response, id, val, true, expires);
    }

    public static void addCookie(HttpServletRequest request, HttpServletResponse response, String id, Object val) {
        addCookie(request, response, id, val, true, -1);
    }

    public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String id) {
        addCookie(request, response, id, (Object)null, true, 0);
    }

    public static String getUidFromCookie(HttpServletRequest request) {
        Cookie c = findCookie(request, "uid", true);
        return c == null ? null : c.getValue();
    }

    public static String getAccessTokenFromCookie(HttpServletRequest request) {
        Cookie c = findCookie(request, "tk", true);
        return c == null ? null : c.getValue();
    }
}

